<template>
    <div style="border: 1px solid #ccc;">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="content" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated" />
    </div>
</template>

<script setup>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Boot } from '@wangeditor/editor';
import { reactive, ref, onBeforeUnmount, onMounted, computed } from 'vue';
// editor为空获取value值存在"<p><br></p>"，在表单中无法校验，借助于插件解决
let withEmptyHtml = (editor) => {
    const { getHtml } = editor
    const newEditor = editor
    newEditor.getHtml = () => {
        if (newEditor.isEmpty()) {
            return ''
        }
        return getHtml()
    }
    return newEditor
}
// 注册插件
Boot.registerPlugin(withEmptyHtml);

let editorRef = ref(null)
let toolbarConfig = ref({})
let mode = ref('simple')// or 'default'
let editorConfig = reactive({
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            // 自定义添加http
            server: 'http//:localhost:3001/upload/editor/',
            // 自定义添加headers
            headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
            // form-data fieldName ，默认值 'wangeditor-uploaded-image'
            fieldName: 'file',
        }
    }
})
// 定义props
let props = defineProps({
    modelValue: {
        type: String,
        default: ""
    },
})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 发射事件
let emit = defineEmits(['update:modelValue']);
let content = computed({
    set: function (newValue) {
        emit('update:modelValue', newValue);
    },
    get: function () {
        return props.modelValue;
    }
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>

<style lang="less"></style>